<template>
	<!-- 自定义导航栏 -->
	<CustomNavBar title="聊天页面,在这里可以和朋友进行聊天" />
	<up-cell-group>
		<up-cell style="text-align: center;">
			<template #title>
				<view class="u-slot-title">
					<text class="u-cell-text">正在和{{ chatUsername }}聊天</text>
				</view>
			</template>
		</up-cell>
	</up-cell-group>
	<up-cell-group style="margin-bottom: 20vh; margin-top: 2vh">
		<view v-for="message in messages" :key="message.id">
			<!-- 如果是信息的consumer是本人则是接收信息 -->
			<up-cell center v-if="user.userAccount === message.consumer">
				<template #icon>
					<up-avatar :src="chatUser[0]?.avatarUrl" size="50" />
				</template>
				<template #title>
					<view class="left_frame">
						<view class="left_triangle"></view>
						<view class="left_rotationtiao">{{ message.content }}</view>
					</view>
				</template>
			</up-cell>

			<!-- 如果是信息的consumer是聊天对象则是发送信息 -->
			<up-cell center v-if="chatUserAccount === message.consumer">
				<template #icon>
					<up-avatar :src="chatUser[0]?.avatarUrl" size="50" />
				</template>
				<template #title>
					<view class="frame">
						<view class="triangle"></view>
						<view class="rotationtiao">{{ message.content }}</view>
					</view>
				</template>
			</up-cell>
		</view>
	</up-cell-group>
			<up-input v-model="content" type="textarea" :rows="1" placeholder="请输入信息" border autosize />
			<up-button type="primary" @click="send">发送</up-button>

</template>

<script setup lang="ts">
	import CustomNavBar from '@/components/CustomNavBar.vue';
	import { onMounted, onBeforeUnmount, ref } from 'vue';
	import { getCurrentUser } from '@/services/user'; // 修改路径适配 UniApp 项目结构
	import { myWebSocket } from '@/config/myWebSocket';

	const user = ref('');
	const socket = ref(null);
	const messages = ref([]);
	const chatUserAccount = ref('');
	const chatUser = ref([]);
	const content = ref('');
	const chatUsername = ref('');

	/**
	 * 接收聊天的用户
	 */
	function onLoad(options) {
		getCurrentUser().then(currentUser => {
			user.value = currentUser;
			chatUserAccount.value = options.userAccount; // 获取路由参数
			console.log('接收到messages', messages.value);
			init()
		});
	}


	/**
	 * 初始化
	 */
	const init = () => {
		console.log('聊天页面的聊天对象', chatUserAccount.value);

		let userAccount = user.value.userAccount;
		if (typeof WebSocket === 'undefined') {
			uni.showToast({
				title: '浏览器不支持WebSocket',
				icon: 'none',
			});
		} else {
			uni.showToast({
				title: '浏览器支持',
				icon: 'success',
			});
			let socketUrl = `${myWebSocket.url}${userAccount}`;
			socket.value = new WebSocket(socketUrl);

			socket.value.onopen = () => {
				console.log('WebSocket连接成功');
			};

			socket.value.onmessage = (msg) => {
				let data = JSON.parse(msg.data);
				console.log('data', data);

				if (data.userList) {
					chatUser.value = data.userList.filter(
						(user) => user.userAccount === chatUserAccount.value
					);
					console.log('聊天用户', chatUser.value);
					chatUsername.value = chatUser.value[0]?.username || '';
				} else {
					if (data.consumer === '0') {
						uni.showToast({
							title: '对方已断开连接,3s后退出',
							icon: 'none',
						});
						setTimeout(() => {
							uni.navigateBack(); // 返回上一页
						}, 3000);
					}
					// 如果 data 中没有 userList 代表这是一个信息
					if (data.consumer === userAccount) {
						messages.value.push(data);
						uni.pageScrollTo({
							scrollTop: 99999, // 滚动到页面底部
							duration: 300,
						});
					}
				}
			};

			socket.value.onclose = () => {
				console.log('WebSocket连接已关闭');
			};

			socket.value.onerror = (err) => {
				console.error('WebSocket连接错误', err);
				uni.showToast({
					title: 'WebSocket连接失败',
					icon: 'none',
				});
			};
		}
	};

	/**
	 * 发送信息
	 */
	const send = () => {
		if (!chatUserAccount.value) {
			uni.showToast({
				title: '发送信息失败',
				icon: 'none',
			});
			return;
		}

		if (!content.value.trim()) {
			uni.showToast({
				title: '信息为空',
				icon: 'none',
			});
			return;
		}

		let message = {
			userAccount: user.value.userAccount,
			consumer: chatUserAccount.value,
			content: content.value,
		};

		socket.value.send(JSON.stringify(message));
		messages.value.push({
			consumer: chatUserAccount.value,
			content: content.value,
		});

		content.value = '';
		uni.pageScrollTo({
			scrollTop: 99999, // 滚动到页面底部
			duration: 300,
		});
	};
</script>

<style scoped>
	.left_frame {
		display: flex;
		align-items: center;
	}

	.left_triangle {
		width: 0;
		height: 0;
		border-top: 10px solid transparent;
		border-bottom: 10px solid transparent;
		border-right: 10px solid #ddd;
		margin-right: 5px;
	}

	.left_rotationtiao {
		background-color: #ddd;
		border-radius: 10px;
		padding: 5px 10px;
	}

	.triangle {
		width: 0;
		height: 0;
		border-top: 10px solid transparent;
		border-bottom: 10px solid transparent;
		border-left: 10px solid #007aff;
		margin-left: 5px;
	}

	.rotationtiao {
		background-color: #007aff;
		color: #fff;
		border-radius: 10px;
		padding: 5px 10px;
	}
</style>